package util
{
	import event.AssetsEvent;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	
	public class AssetsManager extends EventDispatcher
	{
		private static var _instance:AssetsManager;
		
		public function AssetsManager( singleton:SingletonClass ){}
		
		/**
		 *  得到全局唯一的AssetsManager类实例
		 */		
		public static function get instance():AssetsManager
		{
			if( _instance == null )_instance = new AssetsManager( new SingletonClass() );
			
			return _instance;
		}
		
		/**
		 * 加载图片并缓存 
		 * @param url	加载图片路径
		 * @param id	加载请求者的标识符
		 */		
		public function loadImage( url:String, id:String ):void
		{
			
				var loader:Loader = new Loader();
				//将url以及id暂存于Loader的name属性中，以下划线分隔各个信息
				loader.name = url + "|" + id;
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageComplete);
				loader.load( new URLRequest( url ) );
			
		}
		
		public function onImageComplete(e:Event):void {
			var assetsEvent:AssetsEvent = new AssetsEvent("loadComplete");
			var loadInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			
			var info:Array = loadInfo.loader.name.split('|');
			var name:String = info[0];//下划线前的字符串是加载路径
			var id:String = info[1];//下划线后的字符串是id
			
			assetsEvent.id = id;
			
			assetsEvent.loadedBitmapData = (loadInfo.content as Bitmap).bitmapData;
			dispatchEvent(assetsEvent);
		}
	}
}
class SingletonClass{}